import { Slot, component$, useSignal, useStyles$, useVisibleTask$ } from "@builder.io/qwik"
import type { SpinProps } from "./types"
import styles from './index.css?inline';

const Spin = component$<SpinProps>((props) => {
    useStyles$(styles)
    const timer = useSignal<any>();
    const spinningDone = useSignal<boolean>(false);

    useVisibleTask$(({ track }) => {
        track(() => props.spinning);
        clearTimeout(timer.value);
        // 延迟显示加载动画
        if (!props.spinning) {
            timer.value = setTimeout(() => {
                spinningDone.value = false;
            }, 500);
        } else spinningDone.value = true;
    })

    const { spinning = true, wrapperClassName, size = "default" } = props;
    return (
        <div class={["qrui-spin relative", wrapperClassName]}>
            <div style={{
                width: spinningDone.value ? "100%" : 0,
                height: spinningDone.value ? "100%" : 0,
                opacity: spinning ? 0.5 : 0
            }} class="qrui-spin-wrapper flex items-center justify-center absolute top-0 left-0">
                <div class={["qrui-spin-container", `qrui-spin-${size}`]}>
                    <div class="qrui-spin-dot qrui-spin-dot-spin">
                        <i class="qrui-spin-dot-item"></i>
                        <i class="qrui-spin-dot-item"></i>
                        <i class="qrui-spin-dot-item"></i>
                        <i class="qrui-spin-dot-item"></i>
                    </div>
                    <div class="qrui-spining-content">
                        <Slot name="tip" />
                    </div>
                </div>
            </div>
            <Slot />
        </div>
    )
})

export default Spin